<?php

namespace App\Models;

use App\Admin\Controllers\TeamUserController;
use App\Models\UserModel;
use App\Services\Api\WorkService;
use Illuminate\Database\Eloquent\Model;
use App\Models\BookModel;
use Illuminate\Support\Facades\DB;
use Tests\Models\User;
use Illuminate\Support\Facades\Cache;
use App\Admin\Controllers\AdminApiController;

/**
 * App\Models\StudyModel
 *
 * @property int $id
 * @property int $user_id 用户ID
 * @property int $activity_class_id 活动Id
 * @property int $article_id 章节ID
 * @property int $class_work_id 活动堂任务ID
 * @property int $work_id 总任务表ID
 * @property string $work_content 提交 文字/富文本 内容
 * @property string $work_url 提交的文件路径
 * @property float|null $type 任务类型 1文字 2音频
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel whereActivityClassId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel whereArticleId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel whereClassWorkId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel whereType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel whereUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel whereWorkContent($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel whereWorkId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StudyModel whereWorkUrl($value)
 * @mixin \Eloquent
 */
class StudyModel extends Model
{
    //学习记录表
    protected $table='study';

    protected $casts = [
    //  'study_json_content'=>'json',
    ];

    protected $fillable=[
        'id',
        'user_id',
        'key_id',
        'article_id',
        'class_work_id',
        'work_id',
        'class_type',
        'study_json_content',
        'study_url',
        'study_content',
        'is_opend',
        'type',
        'playtime',
        'is_draft',
        'team_id',
        'created_at'
    ];

    //关联书本
    public function Book(){
        $this->belongsTo(BookModel::class,'book_id','id');
    }

    //关联用户
    public function user(){
        return $this->belongsTo(UserModel::class,'user_id','id');
    }

    public function article(){
        return $this->belongsTo(ArticleModel::class,'article_id','id');
    }

    public function getWorkUrlAttribute($value){
        return oss_domain().'/'.$value;
    }

    //study_url
    public function getStudyUrlAttribute($value){
        if(empty($value)){
            return '';
        }else{
            return oss_domain().'/'.$value;
        }
    }

    public function work(){
        return $this->belongsTo(WorkModel::class,'work_id','id');
    }

    public function add_work($data){
        //dd($data);die;
        return $this->create($data);
    }

    public function edit_work($id,$data){
        //dd($data);die;
        return $this->where('id',$id)->update($data);
    }

    public function support(){
        return $this->hasMany(Support::class,'study_id','id');
    }

    public function my_support(){
        return $this->hasOne(Support::class,'study_id','id');
    }

    //所有点赞的人头像
    public function all_support_avatar(){
        return $this->belongsToMany(UserModel::class,'support',
            'study_id', 'user_id');
    }

    public function study_commnet(){
        return $this->hasMany(StudyComment::class,'study_id','id');
    }

    public function getStudyJsonContentAttribute($value){
       // dd(json_decode($value));
        return json_decode($value);
    }

    //改为我未完成的作业
    public function my_work($user_id,$type=[1,2,3,4]){
        $work = [];
        $article_ids = [];
        //key_id 是外键ID 这个是设计变动造成的 根据class_type 1对应shs_company_read的id 2对应 shs_activity_class ID 3对应shs_personal_read ID
        $teamObj = ActivityTeamUser::where('user_id',$user_id)
            ->where('team_user_stash',1)
            ->whereIn('team_type',$type)
            ->where('is_Invisible',1)
            ->select(['team_id','key_id','team_type'])
            ->get()
            ->toArray();

        //ini_set('memory_limit', '1024M');
        $today = date("Y-m-d");
        //没办法就重构吧 需求是這樣变
        foreach ($teamObj as $k=>$v){
            //获取缓存
            $redis_key = env('REDIS_KEY_TEAM_WORK').$v['team_id'];
            $work_data = Cache::get($redis_key);
            if(!empty($work_data)){
                $work_data = json_decode($work_data,true);
            }else{
                $api = new AdminApiController();
                $res = $api->redis_team_book_article($v['key_id'],$v['team_type'],$v['team_id']);
                $work_data = Cache::get($redis_key);
                $work_data = json_decode($work_data,true);
            }
            //dd($work_data);
            foreach ($work_data as $kk=>$vv){
                if($kk<= $today){
                    foreach ($vv['work'] as $kkk=>$vvv){
                        //dd($vvv);
                        $mystudy = StudyModel::whereIn('class_type',$type)
                            ->where('key_id',$vvv['key_id'])
                            ->where('article_id',$vvv['article_id'])
                            ->where('type',$vvv['type'])
                            ->count();
                        if($mystudy == 0){
                            //dd($vv);
                            if(!empty($vv['article_title'])){
                                $vvv['article_title'] = $vv['article_title'];
                            }
                            $work[] = $vvv;
                            //
                        }
                        //continue;
                            //->toArray();
                    }
                }
            }
        }

        return $work;

    }

    public function team_user_work($team_id,$type='',$start_time='',$end_time=''){
        //查询用户时间段内提交的内容
        $team_user = ActivityTeamUser::where('team_id',$team_id)
            //->pluck('user_id')
                ->where('team_user_stash',1)
                ->get()
                ->toArray();

        $user_ids = array_column( $team_user,'user_id');
        $key_ids = array_column( $team_user,'key_id');

        $team_user = UserModel::whereIn('id',$user_ids)
            ->select([
                'id',
                'nickname',
                'avatar',
            ])
            ->with([
                'study'=>function($q)use($key_ids,$start_time,$end_time,$type){
                    $q->select([
                        'id',
                        'user_id',
                        'type',
                        'study_json_content',
                        'study_url',
                        'work_id',
                        'study_content',
                    ])
                        ->whereBetween('created_at',[$start_time,$end_time])
                        ->where('class_type',$type)
                        ->whereIn('key_id',$key_ids);
                },
            ])
            ->get()
            ->toArray();
        if(count($team_user) > 0){
            foreach ($team_user as $k =>$v){
                if(!empty($team_user['study'])){
                    unset($team_user[$k]);
                }
            }
        }

        return $team_user;
    }

    public function my_finish_work($user_id,$class_type,$work_type){
        if(!empty($class_type)){
            $where_class_type[]=$class_type;
        }else{
            $where_class_type = [1,2,3,4];
        }
        if(!empty($work_type)){
            $where_work_type[]=$work_type;
        }else{
            $where_work_type=[1,2,3,4];
        }
        //dd($class_type,$work_type);die;
        return $this->where('user_id',$user_id)
            ->whereIn('class_type',$where_class_type)
            ->whereIn('type',$where_work_type)
            ->where('is_draft',2)
            ->select([
                'id',
                'article_id',
                'class_work_id',
                'work_id',
                'key_id',
                'type',
                'study_json_content',
                'study_url',
                'class_type',
                'study_content',
                'is_opend',
                'is_draft',
                'created_at',
            ])
            ->with([
                'work'=>function($q){
                    $q->select([
                        'id',
                        'title',
                        'describe',
                        'content_json',
                        'type',
                    ]);

                },
                'article'=>function($q){
                    $q->select([
                        'id',
                        'article_title'
                    ]);
                }
            ])
            ->groupBy('class_work_id','article_id')
            ->paginate(15);

    }

    public function my_study_info($study_id,$user_id,$is_draft){

        $q = $this->where('id',$study_id);
        if(!empty($is_draft)){
            $q = $this->where('id',$study_id)->where('is_draft',$is_draft);
        }
       $data =
           $q ->select([
                'id',
                'article_id',
                'class_work_id',
                'work_id',
                'key_id',
                'type',
                'study_json_content',
                'study_url',
                'class_type',
                'study_content',
                'is_opend',
                'is_draft',
                'playtime',
                'created_at',
            ])
            ->with([
                'work'=>function($q){
                    $q->select([
                        'id',
                        'title',
                        'describe',
                        'content_json',
                        'type',
                    ]);
                },
                'my_support'=>function($q)use($user_id){
                    $q->where('user_id',$user_id);
                },
                'study_commnet'=>function($q){
                    $q->with([
                        'user'=>function($u){
                            $u->select([
                                'id',
                                'nickname',
                                'avatar',
                            ]);
                        }
                    ]);
                },
                'article'=>function($q){
                    $q->select([
                       'id',
                       'article_cover',
                       'article_title',
                       'article_content',
                    ]);
                },
            ])
            ->first()->toArray();
        if($data['class_type'] == 2){
            $data['activity_title'] = ActivityClassModel::where('id',$data['key_id'])->value('class_name');
        }else{
            $data['activity_title'] =$data['work']['title'];
        }
        $data['support_number'] = Support::where('study_id',$study_id)->count();
        $data['time'] = date('Y-m-d');
        return $data;
    }

    public function study_list($class_type,$user_id){
        //查出小組的成員完成的作業

        return $this->whereIn('class_type',$class_type)
            ->where('is_opend',2)
            ->where('is_draft',2)
            ->select([
                'id',
                'user_id',
                'type',
                'class_type',
                'study_json_content',
                'study_url',
                'is_draft',
                'study_content',
                'created_at',
            ])
            ->with([
                'user'=>function($q){
                    $q->select(['id','nickname','avatar']);
                },
                'my_support'=>function($q)use($user_id){
                    $q->where('user_id',$user_id);
                },
            ])
            ->orderBy('created_at','desc')
            ->paginate(15);
    }

    public function study_del($study_id,$user_id){
        return $this->where('id',$study_id)
            ->where('user_id',$user_id)
            ->delete();
    }

    public function study_sort($user_id,$type,$start_time,$end_time,$company_id){

        if(!empty($start_time) && !empty($end_time) && $type==2){
            $activity_ids = ActivityClassModel::whereBetween('start_time',[$start_time,$end_time])
                ->where('company_id',$company_id)
                ->pluck('id')
                ->toArray();
            $team_ids = ActivityTeamUser::where('user_id',$user_id)
                ->where('team_type',$type)
                ->whereIn('key_id',$activity_ids)
                ->pluck('team_id')
                ->toArray();
        }else{
            $team_ids = ActivityTeamUser::where('user_id',$user_id)
                ->where('team_type',$type)
                ->pluck('team_id')
                ->toArray();
        }

        //这里的n+ 查询 有空再改
        $team = ActivityTeamUser::whereIn('team_id',$team_ids)
            ->where('team_type',$type)
            ->select([
                'team_id',
                'user_id',
                'key_id',
           ])
            ->with([
                'user'=>function($q){
                    $q->select([
                       'id',
                       'nickname',
                       'avatar',
                    ]);
                },
                'team'=>function($q){
                    $q->select([
                       'id',
                       'team_name',
                    ]);
                }
            ])
            ->get()
            ->toArray();
        //dd($team);
        $arr=array();
        if (count($team)>0){
            foreach ($team as $k=>$v){
                //dd($v);
               $team[$k]['work_total'] = \DB::table('class_work')
                ->where('key_id',$v['key_id'])
                ->where('class_type',$type)
                   ->count();

                if(!empty($start_time) && !empty($end_time) && $type==2){
                    $team[$k]['study_total'] = \DB::table('study')
                        ->where('key_id',$v['key_id'])
                        ->where('user_id',$v['user_id'])
                        ->whereBetween('created_at',[$start_time,$end_time])
                        ->where('class_type',$type)
                        ->count();
                }else{
                    $team[$k]['study_total'] = \DB::table('study')
                        ->where('key_id',$v['key_id'])
                        ->where('user_id',$v['user_id'])
                        ->where('class_type',$type)->count();
                }

            }

            foreach($team as $k=>$v){
                $arr[$v['team_id']][]=$v;
            }

            $arr = array_merge($arr);
        }
        //dd($arr);
        return $arr;
    }

    public function team_study_sort($team_id,$start_time,$end_time){

        //不優化了 需求不確定
        $team = ActivityTeamUser::where('team_id',$team_id)
            ->select([
                'team_id',
                'user_id',
                'key_id',
                'team_type',
                'created_at',
            ])
            ->with([
                'user'=>function($q){
                    $q->select([
                        'id',
                        'nickname',
                        'avatar',
                    ]);
                },
            ])
            ->get()
            ->toArray();
        $data = [];
        //dd($team);
        if (count($team)>0){
            $number = 0;
            $work_total = \DB::table('class_work')
                ->where('key_id',$team[0]['key_id'])
                ->where('class_type',$team[0]['team_type'])
                ->count();

            foreach ($team as $k=>$v){
                $data['team_user'][$k] = $v;
                $total_clock_percentage = 0;
                //只有六項精進才有时间段统计
                if(!empty($start_time) && !empty($end_time) && $v['team_type']==2){

                    $article_ids = \DB::table('activity_class_article')
                        ->where('class_id',$team[0]['key_id'])
                        ->whereBetween('finish_time',[$start_time,$end_time])
                        ->pluck('article_id')
                        ->toArray();
                   // dd($article_ids);

                    $work_total = \DB::table('class_work')
                        ->where('key_id',$team[0]['key_id'])
                        ->whereIn('article_id',$article_ids)
                        ->where('class_type',$team[0]['team_type'])
                        ->count();
                    //dd($work_total);

                    $data['team_user'][$k]['study_total'] = \DB::table('study')
                        ->where('key_id',$v['key_id'])
                        ->where('user_id',$v['user_id'])
                        ->whereIn('article_id',$article_ids)
                        ->whereBetween('created_at',[$start_time,$end_time])
                        ->where('class_type',$v['team_type'])
                        ->count();

                    $data['team_user'][$k]['work_total'] = $work_total;

                    $number +=  $data['team_user'][$k]['study_total'];

                }else{
                    $data['team_user'][$k]['study_total'] = \DB::table('study')
                        ->where('key_id',$v['key_id'])
                        ->where('user_id',$v['user_id'])
                        ->where('class_type',$v['team_type'])
                        ->count();

                    $data['team_user'][$k]['work_total'] = $work_total;

                    $number += $data['team_user'][$k]['study_total'];
                }

                if($number>0){
                    $total_clock_percentage = round($number/($work_total * count($team)),2) * 100;
                }
                $data['total_clock_percentage'] = $total_clock_percentage;

            }

        }
        //dd($data);
        return $data;
    }
    /**
     * @param $company_id
     * @param $start_time
     * @param $end_time
     *
     * @return array
     */
    public function company_work_record($company_id,$start_time,$end_time){

        //查询符合条件的小组
        $team_ids = TeamBook::where('start_time','<=',$start_time)
            ->orderBy('start_time','desc')
            ->groupBy('team_id')->pluck('team_id')->toArray();

        //查询该完成作业的人
        $teamUserObj = ActivityTeamUser::whereIn('team_id',$team_ids)
            ->select([
                'user_id',
                'team_id',
                'key_id',
            ])
            ->where('team_type',2)
            ->where('team_user_stash',1)
            ->groupBy('user_id')
            //->pluck('user_id')
            ->get()
            ->toArray();

        $user_ids = array_column($teamUserObj,'user_id');
        //$team_ids = array_column($teamUserObj,'team_id');
        $key_ids = array_column($teamUserObj,'key_id');

        $class_work_ids = ClassWorkModel::whereIn('activity_class_id',$key_ids)
            ->pluck('id')
            ->toArray();

        //该完成的作业数
        $work_number = count($class_work_ids);

        $userObj = UserModel::whereIn('id',$user_ids)
            ->select([
                'id',
                'nickname',
                'avatar',
                'created_at',
            ])
            ->get()
            ->toArray();
        //待优化
        $total_clock_percentage = 0;
        if(count($userObj)>0){
            $number = 0;
            foreach ($userObj as $k=>$v){
                $userObj[$k]['finish_study'] = StudyModel::whereIn('class_work_id',$class_work_ids)
                    ->where('user_id',$v['id'])
                    ->where('class_type',2)
                    ->where('created_at','>=',$start_time)
                    ->where('created_at','<=',$end_time)
                    ->count();
                $userObj[$k]['not_finish_study'] = $work_number - $userObj[$k]['finish_study'];
                $number +=$userObj[$k]['finish_study'];
            }
            //总打卡率
            //dd($number,$work_number,count($userObj));
            if($number>0){
                $total_clock_percentage = round($number/($work_number * count($userObj)),2) * 100;
            }
            
        }
        return [
            'user'=>$userObj,
            'total_clock_percentage'=> $total_clock_percentage,
        ];

    }

    public function company_read_work_record($company_id,$start_time,$end_time){

        //查询符合条件的小组
        $team_ids = TeamBook::where('start_time','<=',$start_time)
            ->orderBy('start_time','desc')
            ->groupBy('team_id')
            ->pluck('team_id')->toArray();
        //dd($team_ids);

        //查询该完成作业的人
         $teamUserObj = ActivityTeamUser::whereIn('team_id',$team_ids)
             ->select([
                 'user_id',
                 'team_id',
                 'key_id',
             ])
            ->where('team_type',1)
            ->where('team_user_stash',1)
            ->groupBy('user_id')
            //->pluck('user_id')
            ->get()
            ->toArray();
        $user_ids = array_column($teamUserObj,'user_id');
        //$team_ids = array_column($teamUserObj,'team_id');
        //$key_ids = ActivityTeamModel::whereIn('id',$team_ids)->value('key_id');
        $key_ids =  array_column($teamUserObj,'key_id');

        $class_work_ids = ClassWorkModel::whereIn('company_read_id',$key_ids)
            ->pluck('id')
            ->toArray();

        //该完成的作业数
        $work_number = count($class_work_ids);

        $userObj = UserModel::whereIn('id',$user_ids)
            ->select([
                'id',
                'nickname',
                'avatar',
                'created_at',
            ])
            ->get()
            ->toArray();
        //待优化
        $total_clock_percentage = 0;
        if(count($userObj)>0){
            $number = 0;
            foreach ($userObj as $k=>$v){
                $userObj[$k]['finish_study'] = StudyModel::whereIn('class_work_id',$class_work_ids)
                    ->where('user_id',$v['id'])
                    ->where('class_type',1)
                    ->where('created_at','>=',$start_time)
                    ->where('created_at','<=',$end_time)
                    ->count();
                $userObj[$k]['not_finish_study'] = $work_number - $userObj[$k]['finish_study'];
                $number +=$userObj[$k]['finish_study'];
            }
            //总打卡率
            //dd($number,$work_number,count($userObj));
            if($number>0){
                $total_clock_percentage = round($number/($work_number * count($userObj)),2) * 100;
            }

        }
        return [
            'user'=>$userObj,
            'total_clock_percentage'=> $total_clock_percentage,
        ];

    }

    public function personal_read_work_record($company_id,$start_time,$end_time){

        //查询符合条件的小组
        $team_ids = TeamBook::where('start_time','<=',$start_time)
            //->where('start_time','=',$end_time)
            ->orderBy('start_time','desc')
            ->groupBy('team_id')
            ->pluck('team_id')->toArray();
        //dd($team_ids);

        //查询该完成作业的人
        $teamUserObj = ActivityTeamUser::whereIn('team_id',$team_ids)
            ->select([
                'user_id',
                'team_id',
                'key_id',
            ])
            ->where('team_type',3)
            ->where('team_user_stash',1)
            ->groupBy('user_id')
            //->pluck('user_id')
            ->get()
            ->toArray();
        //dd($teamUserObj);
        $user_ids = array_column($teamUserObj,'user_id');
        //$team_ids = array_column($teamUserObj,'team_id');
        //$key_ids = ActivityTeamModel::whereIn('id',$team_ids)->value('key_id');
        $key_ids =  array_column($teamUserObj,'key_id');

        $class_work_ids = ClassWorkModel::whereIn('personal_read_id',$key_ids)
            ->pluck('id')
            ->toArray();

        //该完成的作业数
        $work_number = count($class_work_ids);

        $userObj = UserModel::whereIn('id',$user_ids)
            ->select([
                'id',
                'nickname',
                'avatar',
                'created_at',
            ])
            ->get()
            ->toArray();
        //待优化
        $total_clock_percentage = 0;
        if(count($userObj)>0){
            $number = 0;
            foreach ($userObj as $k=>$v){
                $userObj[$k]['finish_study'] = StudyModel::whereIn('class_work_id',$class_work_ids)
                    ->where('user_id',$v['id'])
                    ->where('class_type',3)
                    ->where('created_at','>=',$start_time)
                    ->where('created_at','<=',$end_time)
                    ->count();
                $userObj[$k]['not_finish_study'] = $work_number - $userObj[$k]['finish_study'];
                $number +=$userObj[$k]['finish_study'];
            }
            //总打卡率
            //dd($number,$work_number,count($userObj));
            if($number>0){
                $total_clock_percentage = round($number/($work_number * count($userObj)),2) * 100;
            }

        }
        return [
            'user'=>$userObj,
            'total_clock_percentage'=> $total_clock_percentage,
        ];

    }

    /**
     * @param $user_id
     * 塾生学习需要完成的作业
     */
    public function my_personal_work($user_id){
            $new_data = [];
            $data = PersonalRead::select([
                    'id',
                    'personal_title',
                    'book_id',
                ])
                ->with([
                    'class_work'=>function($q)use($user_id){
                        $q->select([
                            'id',
                            'work_id',
                            'personal_read_id',
                            //\DB::raw('count(*) class_work_number'),
                        ])->with([
                            'study_work'=>function($q)use($user_id){
                                $q  ->where('user_id',$user_id)
                                    ->select([
                                    'id',
                                    'class_work_id',
                                    'key_id',
                                    \DB::raw('count(*) study_work_number'),
                                ]);
                            },

                        ]);
                    },
                 ])
                ->get()
                ->toArray();
           // dd($data);
        $class_work_number = 0;
        $study_work_number = 0;
        if(count($data)>0){
            foreach ($data as $k=>$v){
                //dd($v);
                $class_work_number += count($v['class_work']);
                if(count($v['class_work'])>0){
                    foreach ($v['class_work'] as $kk=>$vv){
                        //dd($vv);
                        if(empty($v['study_work']['id'])){
                            $data[$k]['class_work'][$kk]['study_work'] = [];
                        }else{
                            $study_work_number += 1;
                        }
                    }
                }

            }
        }

        $new_data['personal_work'] = $data;
        $new_data['class_work_number'] = $class_work_number;
        $new_data['study_work_number'] = $study_work_number;

        return $new_data;
       //dd($new_data);
    }
}
